<template>
  <div class="setRole">
    <el-dialog center="" title="分配权限" :visible="showRole" @close="cancel">
      <el-tree
        ref="tree"
        :data="treeData"
        :props="props"
        show-checkbox
        check-strictly
        default-expand-all
        node-key="id"
      >
      </el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="setRolePerm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getSysPermissionApi } from '../../../api/permission'
import { getRolePermApi, setRolePermApi } from '../../../api/role'
export default {
  name: 'setRole',
  props: ['showRole', 'id'],
  data() {
    return {
      treeData: [],
      props: { label: 'name' },
      checkedPerm: []
    }
  },
  methods: {
    async setRolePerm() {
      this.checkedPerm = this.$refs.tree.getCheckedKeys()
      await setRolePermApi({
        id: this.id,
        permIds: this.checkedPerm
      })
      this.$message.success('分配成功')
      this.$emit('update:showRole', false)

      this.$store.dispatch('user/getUserInfo')
    },

    //  获取 对应Id角色 权限
    async getRolePerm(id) {
      const res = await getRolePermApi(id)

      this.$refs.tree.setCheckedKeys(res.permIds)
    },
    // 数据转treeData结构
    tranTreeData(arr, str) {
      return arr.filter(item => {
        if (item.pid === str) {
          item.children = this.tranTreeData(arr, item.id)
          return true
        }
      })
    },
    // 获取所有权限
    async getSysPermission() {
      const res = await getSysPermissionApi()
      this.treeData = this.tranTreeData(res, '0')
    },
    // 关闭弹窗
    cancel() {
      this.$emit('update:showRole', false)
      this.$refs.tree.setCheckedKeys([])
    }
  },
  created() {
    this.getSysPermission()
  }
}
</script>

<style>
</style>